package com.iaiai.imail.activity;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.iaiai.imail.core.IActivity;
import com.iaiai.imail.core.IServiceFactory;
import com.iaiai.imail.entity.Email;

public class MainActivity extends IActivity {

	private ListView listView;

	private List<Email> list;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		setTitleText(getResources().getString(R.string.app_name));

		findViewById(R.id.create).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent activity = new Intent(MainActivity.this, CreateActivity.class);
				Bundle bundle = new Bundle();
				bundle.putBoolean("create", true);
				activity.putExtras(bundle);
				startActivity(activity);
				finish();
				overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			}
		});

		listView = (ListView) findViewById(R.id.listView);

		dialog.show();
		execHandle(new Handler() {
			@Override
			public void query() {
				getData();
			}
		}, new Runnable() {
			@Override
			public void run() {
				dialog.dismiss();

				listView.setAdapter(new BaseAdapter() {
					@Override
					public int getCount() {
						return list.size();
					}

					@Override
					public Object getItem(int position) {
						return list.get(position);
					}

					@Override
					public long getItemId(int position) {
						return list.get(position).getId().longValue();
					}

					@Override
					public View getView(int position, View convertView, ViewGroup parent) {
						convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item, null);
						TextView title = (TextView) convertView.findViewById(R.id.title);
						title.setText(list.get(position).getAccount());
						return convertView;
					}
				});
				listView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
						Intent activity = new Intent(MainActivity.this, EmailActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("account", list.get(position).getAccount());
						activity.putExtras(bundle);
						startActivity(activity);
						overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
					}
				});
			}
		});
	}

	private void getData() {
		list = IServiceFactory.getInstance().getEmailDao().queryAll();
	}

}
